<?php
/*********************************************************************
 * ADMIN FUNCTIONS FILE
 * 
 * Author: hthieu1110
 * Date: 09/04/2011
 *********************************************************************
 * addPage($pageName):
 * 		create the template files in:
 * 			+ controller
 *      + view
 *      + css
 *  
 **********************************************************************/

require_once dirname(realpath(__FILE__)).'./../../config/config.inc.php';
require_once HELPER_PATH.'file.helper.php';

try {
  $Db = new Db();
} catch (Exception $e) {
  die('Cannot connect to DB');
}

//-----------------------------------------------------------------------
function genRegionsTownsCache() {
  global $Db;
  $queryRegion = 'SELECT * from departement';
  $departements = $Db->selectTable($queryRegion);
  $departementCacheDir = CACHE_PATH.'departement/';

  $departementsExported = var_export($departements, true);

  $departementsContent = 
'<?php
$departementsCached = '.$departementsExported.';
?>';
  
  file_put_contents($departementCacheDir.'fr.departements.php', $departementsContent);

  foreach($departements as $departement) {
    $queryTown = 'SELECT * FROM town WHERE departementCode = \''.$departement['code'].'\'';
    $towns = $Db->selectTable($queryTown);
    
    $townsExported = var_export($towns, true);
    
    $townsContent = 
'<?php
$townsCached = '.$townsExported.';
?>';
    
    file_put_contents($departementCacheDir.$departement['code'].'.towns.php', $townsContent);
    file_put_contents($departementCacheDir.$departement['code'].'.towns.json', json_encode($towns));
  }
}

//-----------------------------------------------------------------------
function genCategoriesCache() {
  $queryParent = 'SELECT * FROM category WHERE parentCategoryId = 0';
  
  $categoryParents = Db::execQuery('select', $queryParent, true);

  $categories = array();
  
  foreach($categoryParents as $categoryParent) {
    
    $categoryParentId = $categoryParent['id'];
    $categoryParentName = $categoryParent['name'];
    
    $queryChild = 'SELECT * FROM category WHERE parentCategoryId = '.$categoryParentId;
  
    $categoryChilds = Db::execQuery('select', $queryChild, true);
    
    $categories[] = array('id'=>$categoryParentId, 'name'=>$categoryParentName, 'childs'=>$categoryChilds);
  }
  
  $categoryCachePath = CACHE_PATH.'category.cache.php';
  $categoriesExported = var_export($categories, true);
  
  file_put_contents($categoryCachePath, "<?php \$_categoriesCached =\n".$categoriesExported." ?>");
}

//-----------------------------------------------------------------------
function importCategories() {
  $categorySourcePath = dirname(realpath(__FILE__)).'/../data/category/categories.tsv';
  
  $categories = file($categorySourcePath);
  
  foreach($categories as $category) {
    //if line is empty then pass
    if (trim($category) == "") continue;
    
    list($catId, $parentCatId, $name) = explode("\t", trim($category));
    
    $query = sprintf("INSERT INTO category (id, parentCategoryId, name) VALUES('%d','%d','%s')",
              mysql_escape_string($catId),
              mysql_escape_string($parentCatId),
              mysql_escape_string(trim($name)));
              
    try {
      Db::execQuery('insert', $query);
    } catch (Exception $e) {
      echo $e->getMessage();
    }
  }
  
  return true;
}

//-----------------------------------------------------------------------
function getFields($tableName){
	$query = sprintf('SELECT * FROM %s', mysql_escape_string($tableName));

  $fields = Db::execQuery('select', $query, true);
	
	return $fields;
}

//-----------------------------------------------------------------------
function addPage($pageName){
	//check if the needed files exist?
	$filesCreated = array();

	//check controller
	if(!file_exists(CONTROLLER_PATH.$pageName.'.php')){
		if (createController($pageName)) $filesCreated[] = 'controller';
	}
	
	//check view
	if(!file_exists(VIEW_PATH.$pageName.'.template.php')){
		if (createView($pageName)) $filesCreated[] = 'view';
	}
	//check css
	if(!file_exists(CSS_PATH.$pageName.'.css')){
		if (createCss($pageName)) $filesCreated[] = 'css';
	}
	
	return $filesCreated;
}

//-----------------------------------------------------------------------
function createController($controllerName){
	//if controller exists then return false
	if(file_exists(CONTROLLER_PATH.$controllerName.'.php')) return false;
	
	$template =
'<?php
/*********************************************************************
 * '.strtoupper($controllerName).' CONTROLLER
 * 
 * Author: hthieu1110
 * Date: '.date("d/m/Y").' (generated automatically)
*********************************************************************/
require_once dirname(realpath(__FILE__))."./../../config/config.inc.php";



require_once VIEW_PATH."header.inc.php";
require_once VIEW_PATH."/'.$controllerName.'.template.php";
require_once VIEW_PATH."footer.inc.php";
?>';
	
	//if an error occurs then return false
	if (!file_helper_create_file(CONTROLLER_PATH.$controllerName.'.php', $template)) return false;

	//change mask
	$oldMask = umask(0);
	chmod(CONTROLLER_PATH.$controllerName.'.php', 0777);
	umask($oldMask);
	
	return true;
}

//-----------------------------------------------------------------------
function createCss($cssName){
	//if css exists then return false
	if(file_exists(CSS_PATH.'/'.$cssName.'.css')) return false;
	
	$template = '/* Generated automatically at '.date("d/m/Y").' */';
	
	//if an error occurs then return false
	if (!file_helper_create_file(CSS_PATH.$cssName.'.css', $template)) return false;
	
	//change mask
	$oldMask = umask(0);
	chmod(CSS_PATH.$cssName.'.css', 0777);
	umask($oldMask);
	
	return true;
}

//-----------------------------------------------------------------------
function createView($viewName){
	//if css exists then return false
	if(file_exists(VIEW_PATH.$viewName.'.template.php')) return false;
	
	$template = '<!-- Generated automatically at '.date("d/m/Y").' -->';
	
	//if an error occurs then return false
	if (!file_helper_create_file(VIEW_PATH.$viewName.'.template.php', $template)) return false;

	//change mask
	$oldMask = umask(0);
	chmod(VIEW_PATH.$viewName.'.template.php', 0777);
	umask($oldMask);
	
	return true;
}

//-----------------------------------------------------------------------
function getFranceRegionsTowns() {
  require_once './function.php';
  set_time_limit(9999);
  
  $url = "http://www.gauloise.com/";
  $html = file_get_contents($url);
  $html = preg_replace('/[ \r\t\n]+/', ' ', $html);

  $begin = '<div style="width:200px;';
  $end = '</div>';

  //create regions file
  $fileRegionHandle = fopen(dirname(realpath(__FILE__)).'./../data/regions.tsv', 'wb');
  
  $regionBruts = stringBetween($html, $begin, $end);
  foreach($regionBruts as $regionBrut) {
    $regionLink = trim(cut_str($regionBrut, '<a href="', '"'));
    $regionCode = trim(cut_str($regionBrut, 'margin-left:10px;">', '<'));
    $regionName = trim(cut_str($regionBrut, '"">', '<'));
    $regionCode = trim(str_replace(array(')','('), '', $regionCode));
    
    //write to regions file
    fwrite($fileRegionHandle, $regionCode."\t".$regionName."\n");
    
    $html = file_get_contents($regionLink);
    
    $begin = '<div style="width:410px;';
    $end = '</div>';
    
    $townBruts = stringBetween($html, $begin, $end);
    
    //create towns file
    $fileTownHandle = fopen(dirname(realpath(__FILE__)).'./../data/'.$regionCode.'.tsv', 'wb');
      
    foreach($townBruts as $townBrut) {
      $townCode = trim(cut_str($townBrut, 'margin-left:10px;">', '<'));
      $townName = trim(cut_str($townBrut, 'html">', '<'));
      $townCode = trim(str_replace(array(')','('), '', $townCode));
      
      //write to towns file
      fwrite($fileTownHandle, $townCode."\t".$townName."\n");
    }
    fclose($fileTownHandle);
  }
  fclose($fileRegionHandle);
}
  
//-----------------------------------------------------------------------
function importFranceRegions() {
  require_once dirname(realpath(__FILE__)).'./../../model/Db.class.php';
  
  global $Db;
  
  $regions= file(dirname(realpath(__FILE__)).'./../data/region/regions.tsv');

  foreach($regions as $region) {
    list($regionCode, $regionName) = explode("\t", $region);
    list($regionCode, $regionName) = array(trim($regionCode), trim($regionName));
    
    $regionName = utf8_encode(htmlspecialchars($regionName, ENT_QUOTES));
    
    $query = sprintf("INSERT INTO departement (code, name) VALUES('%s', '%s')",
                    mysql_escape_string($regionCode),
                    mysql_escape_string($regionName));
    $Db->insert($query);
  }
  
  return true;
}

//-----------------------------------------------------------------------
function importFranceTowns() {
  global $Db;
  
  if ($dirHandle = opendir(dirname(realpath(__FILE__)).'/../data/town/')) {
    while (false !== ($file = readdir($dirHandle))) {
      if ($file != "." && $file != "..") {
        if ($file == 'regions.tsv') continue;
        
        $regionCode = str_replace('.tsv', '', trim($file));
        
        $towns = file(dirname(realpath(__FILE__)).'/../data/town/'.$file);
        foreach($towns as $town) {
          list($townCode, $townName) = explode("\t", $town);
          list($townCode, $townName) = array(trim($townCode), trim($townName));
          
          $townName = utf8_encode(htmlspecialchars($townName, ENT_QUOTES));
          
          $query = sprintf("INSERT INTO town (code, departementCode, name) VALUES('%s', '%s', '%s')",
                          mysql_escape_string($townCode),
                          mysql_escape_string($regionCode),
                          mysql_escape_string($townName));
      
          $Db->insert($query);
        }
      }
    }
    closedir($dirHandle);
  }
  return true;
}
  
  